<template>
  <div id="client">
    <p style="position: relative; right: 180px; scale: 0.8; width: 1700px">
      &nbsp;&nbsp;&nbsp;单据日期：
      <el-date-picker
        type="daterange"
        v-model="DjDateRange"
        align="right"
        unlink-panels
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handleDateChange2"
      >
      </el-date-picker>

      &nbsp;&nbsp;&nbsp; 单据编号：<el-input
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="单据编号"
        v-model="select.searchQuery"
        clearable
      >
      </el-input>
      &nbsp;&nbsp;&nbsp; 供应商：<el-input
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="请选择供应商"
        v-model="proName"
        clearable
      ></el-input>
      <el-button
        style="margin-left: -20px; margin-right: 10px"
        @click="dialogShow = true"
        >...</el-button
      >

      &nbsp;&nbsp;&nbsp; 业务员：
      <el-select
        v-model="select.yid"
        placeholder="业务员"
        style="width: 180px; margin-left: 10px; margin-right: 20px"
      >
        <el-option label="(空)" :value="0"> </el-option>
        <el-option
          v-for="item in employee"
          :key="item.employeeId"
          :label="item.employeeName"
          :value="item.employeeId"
        >
        </el-option>
      </el-select>

      &nbsp;&nbsp;&nbsp;
      <el-button type="primary" @click="selectPage(1, 100)">查询</el-button>
    </p>
    <p style="float: right; scale: 0.8; margin-top: 20px; margin-right: 60px">
      <el-button @click="save()">发票登记</el-button>
      <el-button @click="goto('Indoc')">开票记录</el-button>
      <el-button>导出</el-button>
      <el-divider></el-divider>
    </p>
    <el-table
      height="300px"
      :data="pageInfo ? pageInfo.list : []"
      border
      style="width: 100%; font-size: 13px"
      :row-class-name="tableRowClassName"
      @selection-change="handleSelectionChange"
      show-summary
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="createDate" label="单据日期" width="150">
      </el-table-column>
      <el-table-column prop="documentNumber" label="单据编号" width="330">
      </el-table-column>
      <el-table-column prop="orderNumber" label="关联购货订单号" width="330">
      </el-table-column>
      <el-table-column prop="proName" label="供应商" width="120">
      </el-table-column>
      <el-table-column prop="singleName" label="源制单人" width="120">
      </el-table-column>
      <el-table-column prop="quantity" label="数量" width="120">
        <template slot-scope="scope">
          {{ Math.abs(scope.row.quantity) }}
        </template>
      </el-table-column>
      <el-table-column prop="writtenOffAmount" label="已付款" width="120">
        <template slot-scope="scope">
          {{ Math.abs(scope.row.writtenOffAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="付款状态">
        <template slot-scope="scope">
          <span v-if="scope.row.purType == 1">
            <div v-if="scope.row.writtenOffAmount == 0">未付款</div>
            <div v-else-if="scope.row.writtenOffAmount === scope.row.amount">
              全部付款
            </div>
            <div v-else>部分付款</div>
          </span>
          <span v-else>
            <div v-if="scope.row.writtenOffAmount == 0">未退款</div>
            <div v-else-if="scope.row.writtenOffAmount === scope.row.amount">
              全部退款
            </div>
            <div v-else>部分退款</div>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="价税合计" width="120">
        <template slot-scope="scope">
          {{ Math.abs(scope.row.amount) }}
        </template>
      </el-table-column>
      <el-table-column prop="invoicedAmount" label="已开票金额" width="120">
        <template slot-scope="scope">
          {{ Math.abs(scope.row.invoicedAmount) }}
        </template>
      </el-table-column>
      <el-table-column prop="noInvoicedAmount" label="未开票金额" width="120">
        <template slot-scope="scope">
          {{ Math.abs(scope.row.noInvoicedAmount) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="thisInvoicedAmount"
        label="本次开票金额"
        width="120"
      >
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.text"
            @blur="handleBlur(scope.row)"
            clearable
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="整单备注" width="120">
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-left: 500px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo ? pageInfo.pageNum : 1"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="pageInfo ? pageInfo.pageSize : 100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo ? pageInfo.total : 0"
    >
    </el-pagination>

    <p style="scale: 0.8; margin-top: 10px; margin-bottom: 10px">
      <span style="color: red">*</span>开票日期：
      <el-date-picker
        v-model="invoice.invoicingDate"
        type="date"
        placeholder="选择日期时间"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      >
      </el-date-picker
      >&nbsp;&nbsp;&nbsp; <span style="color: red">*</span>发票号：<el-input
        style="width: 240px; margin-left: 10px; margin-right: 20px"
        v-model="invoice.invoiceNumber"
        clearable
      >
      </el-input>
      发票金额：<el-input
        style="width: 240px; margin-left: 10px; margin-right: 20px"
        v-model="invoice.invoiceAmount"
        clearable
      >
      </el-input>
    </p>
    <p style="scale: 0.8">
      <span style="color: red">*</span> 发票抬头：<el-input
        style="width: 240px; margin-left: 10px; margin-right: 20px"
        v-model="invoice.invoiceTitle"
        clearable
      >
      </el-input>
      开票备注：<el-input
        style="width: 240px; margin-left: 10px; margin-right: 20px"
        v-model="invoice.invoicingNotes"
        clearable
      >
      </el-input>
      销售方：<el-input
        style="width: 240px; margin-left: 10px; margin-right: 20px"
        v-model="invoice.seller"
        clearable
      >
      </el-input>
    </p>

    <el-dialog top="20px" title="选择供应商" :visible.sync="dialogShow">
      <ProviderChoose ref="choosePro" :dialogShow="dialogShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="yes">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ProviderChoose from "../public_com/ProviderChoose.vue";

export default {
  name: "Invoice",
  components: {
    ProviderChoose,
  },
  data() {
    return {
      DjDateRange: [], //单据日期
      dialogShow: false,
      employee: [],
      pageInfo: null,
      proName: "",
      select: {
        startDate2: "",
        endDate2: "",
        searchQuery: "",
        proId: "",
        yid: "",
        invoiceFlag: "1",
        reviewStatus: "2",
      },
      invoice: {
        invoicingDate: "", //开票日期
        invoiceNumber: "", //开票号
        invoiceAmount: 0, //发票金额
        invoiceTitle: "", //发票抬头
        invoicingNotes: "", //发票备注
        seller: "", //销售方
      },
      selectedRows: "",
    };
  },
  methods: {
    successMessage(msg) {
      this.$message({
        message: msg,
        type: "success",
      });
    },
    errorMessage(msg) {
      this.$message({
        message: msg,
        type: "error",
      });
    },
    save() {
      if (!this.selectedRows || this.selectedRows.length <= 0) {
        this.errorMessage("请选择购货单或购货退货单");
        return;
      }
      if (!this.invoice.invoicingDate) {
        this.errorMessage("请输入开票日期");
        return;
      }

      if (!this.invoice.invoiceNumber) {
        this.errorMessage("请输入发票号");
        return;
      }
      if (!this.invoice.invoiceTitle) {
        this.errorMessage("请输入发票抬头");
        return;
      }

      var details = [];

      this.axios
        .get("/purchase/invoice/vaInvoiceNumber", {
          params: {
            invoiceNumber: this.invoice.invoiceNumber,
          },
        })
        .then((rs) => {

          this.selectedRows.forEach((inquiry, index) => {
            console.log(inquiry)
            details.push({
              purchaseOrderId: inquiry.id,
              thisInvoicedAmount:inquiry.thisInvoicedAmount,
            });
          });

          const formdata = new FormData();

          formdata.append("invoice", JSON.stringify(this.invoice));
          formdata.append("invoiceDetails", JSON.stringify(details));

          if (rs.data.code == 200) {
            this.axios
              .post("/purchase/invoice/addInvoice", formdata)
              .then((rs) => {
                if ((rs.data.code = 200)) {
                  this.successMessage("添加成功");
                  this.letNull();
                  this.selectPage(1, 100);
                } else {
                  this.errorMessage("添加失败");
                }
              });
          } else {
            this.errorMessage("发票号不可以重复");
          }
        });
    },
    letNull() {
      this.invoice = {
        invoicingDate: "", //开票日期
        invoiceNumber: "", //开票号
        invoiceAmount: 0, //发票金额
        invoiceTitle: "", //发票抬头
        invoicingNotes: "", //发票备注
        seller: "", //销售方
      };
      this.selectedRows = "";
    },
    handleSelectionChange(selectedRows) {
      console.log(selectedRows); // 打印当前选中的行数据
      // 你可以在这里处理选中的行数据，例如存储到数据属性中
      this.selectedRows = selectedRows;

      if (this.selectedRows && selectedRows.length > 0) {
        const totalInvoicedAmount = selectedRows.reduce((sum, row) => {
          return sum + parseFloat(row.thisInvoicedAmount);
        }, 0);
        this.invoice.invoiceAmount = totalInvoicedAmount.toFixed(2);
        this.invoice.seller = selectedRows[0].proName;
      } else {
        this.invoice.invoiceAmount = 0;
        this.invoice.seller = "";
      }
    },
    handleBlur(row) {
      // 验证和重置购货单价（假设购货单价可以是浮点数）
      const positiveNumberRegex = /^\d+(\.\d{1,2})?$/; // 匹配正数，小数点最多两位
      if (!positiveNumberRegex.test(row.text) || row.text === "") {
        this.$message({
          showClose: true,
          message: "本次开票金额必须是正数,且小数点后最多两位",
          type: "warning",
        });
        // 将字符串转换为浮点数
        let discountValue = parseFloat(row.text);
        // 如果isNaN，则设置为0
        if (isNaN(discountValue)) {
          row.text = Math.abs(row.noInvoicedAmount);
        } else {
          // 修正为0-100之间的值
          if (discountValue <= 0) {
            row.text = Math.abs(row.noInvoicedAmount);
          } else {
            // 四舍五入到两位小数
            row.text = parseFloat(discountValue.toFixed(2));
          }
        }
      }

      if (row.text > Math.abs(row.noInvoicedAmount) || row.text == 0) {
        this.$message({
          showClose: true,
          message: "本次开票金额必须小于未开票金额,且不等于0",
          type: "warning",
        });
        row.text = Math.abs(row.noInvoicedAmount);
      }

      if (row.purType === 1) {
        row.thisInvoicedAmount = parseFloat(row.text).toFixed(2);
      } else if (row.purType === 2) {
        row.thisInvoicedAmount = -parseFloat(row.text).toFixed(2);
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.purType === 2) {
        return "row-red";
      }
      return "";
    },
    yes() {
      this.dialogShow = false;
      var list = this.$refs.choosePro.selectionList;
      if (list.length <= 0) {
        this.proName = "";
        this.select.proId = "";
        return;
      }
      this.proName = list[0].providerName;
      this.select.proId = list[0].providerId;
    },
    goto(to) {
      this.$router.push(to);
    },
    handleSizeChange(newSize) {
      console.log(`每页 ${newSize} 条`);
      this.findAll(1, newSize);
    },
    handleCurrentChange(newPage) {
      console.log(`当前页: ${newPage}`);
      this.findAll(newPage, this.pageInfo.pageSize);
    },
    selectEm() {
      this.axios({
        url: "/info/employee/listAll",
      }).then((rs) => {
        this.employee = rs.data.list;
      });
    },
    selectPage(pageNum, pageSize) {
      this.axios
        .get("/purchase/purchaseOrder/getPage", {
          params: {
            pageNum,
            pageSize,
            ...this.select,
          },
        })
        .then((rs) => {
          if (rs.data.pageInfo) {
            this.pageInfo = rs.data.pageInfo;
            console.log(this.pageInfo);
            console.log(rs);
            if (rs.data.pageInfo) {
              const list = rs.data.pageInfo.list.map((item) => ({
                ...item,
                noInvoicedAmount: item.amount - item.invoicedAmount,
                thisInvoicedAmount: item.amount - item.invoicedAmount,
                text: Math.abs(item.amount - item.invoicedAmount),
              }));
              this.pageInfo = {
                ...rs.data.pageInfo,
                list,
              };
              console.log(this.pageInfo);
            }
          }
        });
    },
    handleDateChange2(value) {
      if (value) {
        this.select.startDate2 = value[0]; // 起始日期
        this.select.endDate2 = value[1]; // 结束日期
      } else {
        this.select.startDate2 = ""; // 起始日期
        this.select.endDate2 = ""; // 结束日期
      }
    },
  },
  created() {
    this.selectEm();
    this.selectPage(1, 100);
  },
};
</script>

<style>
.el-button el-button--default el-popover__reference {
  margin-right: 20px;
}

.el-table .row-red {
  color: red; /* 设置字体颜色为红色 */
}

tr {
  border: 1px solid black;
}
</style>